<template>
  <view class="my-task-container">
    <!-- <view class="my-task-title">我的任务</view> -->
    <view class="my-task-content">
      <!-- @click="tabClick" -->
      <nut-tabs
        v-model="activeTab"
        :swipeable="true"
        @change="tabChange"
      >
        <nut-tab-pane
          v-for="tab in tabs"
          :key="tab.id"
          :title="tab.title"
        >
          <scroll-view
            scroll-y
            @scrolltolower="loadMore"
          >
            <view
              class="list-item-box"
              v-for="(item, index) in myTaskRecipientList"
              :key="index"
            >
              <view
                class="list-item"
                :class="item?.stausClass"
              >
                <view class="list-item-top">
                  <view class="list-item-icon">
                    <view class="icon-box"> </view>
                    <view class="icon-text">人力</view>
                  </view>
                  <view class="list-item-content">
                    <view class="content-title-box">
                      <view class="content-title-left">
                        <view class="content-title">{{ item.title }}</view>
                        <view
                          v-if="item.taskStatus != null || item.taskStatus != undefined || item.taskStatus != ''"
                          class="list-item-status"
                          :class="item?.stausClass"
                          >{{ officeStatusList[item.taskStatus]?.dictLabel }}</view
                        >
                      </view>
                      <view class="content-user-info">
                        <view class="user">
                          <view class="user-title">发起人</view>
                          <view class="user-name">
                            <img
                              :src="item.avatarUrl"
                              alt=""
                            />
                            <view class="user-name-text">{{ item.nickName }}</view>
                          </view>
                        </view>
                        <view class="time">
                          <view class="time-title">时间</view>
                          <view class="time-text">截止{{ item.finishTime?.substring(5, 16) }}</view>
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
                <view class="list-item-bottom">
                  <view class="list-item-card">
                    <view class="card-item">
                      <text>优先级</text>
                      <text :style="{ color: priorityLevelList[item.priorityLevel - 1]?.color }">{{
                        priorityLevelList[item.priorityLevel - 1]?.text
                      }}</text>
                    </view>
                    <view class="card-item">
                      <text>执行人/部门</text>
                      <nut-avatar-group
                        zIndex="right"
                        max-content=" "
                        size="small"
                      >
                        <nut-avatar
                          v-for="(itm, idx) in item.executorNameList"
                          :key="idx"
                          size="small"
                        >
                          <img
                            :src="itm.avatarUrls"
                            alt=""
                          />
                        </nut-avatar>
                      </nut-avatar-group>
                      <view class="card-item-num"
                        >{{ item.executorNameList.length > 0 ? item.executorNameList.length + "人" : "无" }}
                      </view>
                    </view>
                    <view class="card-item">
                      <text>协作人员</text>
                      <nut-avatar-group
                        zIndex="right"
                        max-content=" "
                        size="small"
                      >
                        <nut-avatar
                          v-for="(itm, idx) in item.collaboratorsNameList"
                          :key="idx"
                          size="small"
                        >
                          <img
                            :src="itm.avatarUrls"
                            alt=""
                          />
                        </nut-avatar>
                      </nut-avatar-group>
                      <view class="card-item-num">{{
                        item.collaboratorsNameList.length > 0 ? item.collaboratorsNameList.length + "人参与其中" : "无"
                      }}</view>
                    </view>
                  </view>
                </view>
                <view class="card-button">
                  <view class="card-button-left">
                    <view
                      v-if="tab.id === 4"
                      class="card-button-left-item"
                      >已催办 <text>3</text> 次，请尽快完成</view
                    >
                  </view>
                  <view
                    class="card-button-right"
                    v-if="item.taskStatus != 2"
                  >
                    <view class="btn-box">
                      <nut-button
                        v-if="item.userId == userId"
                        type="primary"
                        size="small"
                        color="#4f73f3"
                        shape="round"
                        plain
                        @click="handleEditTask(item)"
                      >
                        <text>编辑</text>
                      </nut-button>
                      <nut-button
                        v-else
                        type="primary"
                        size="small"
                        color="#4f73f3"
                        shape="round"
                        plain
                        @click="handleTaskDeails"
                      >
                        <i
                          class="iconfont icon-yanjing"
                          style="font-size: 14px"
                        ></i>
                        <text>查看</text>
                      </nut-button>
                    </view>
                    <view class="btn-box">
                      <nut-button
                        v-if="
                          (item.userId == userId || item.isMyParticipateTask) &&
                          item.taskStatus == 1 &&
                          item.recevieStatus != 1 &&
                          item.isExecutorNameTask
                        "
                        type="primary"
                        size="small"
                        color="#1E74FD"
                        shape="round"
                        @click="handleReceive(item, 2)"
                        >完成任务
                      </nut-button>
                      <nut-button
                        v-if="item.isMyParticipateTask && item.recevieStatus == 0 && item.taskStatus != 2"
                        type="primary"
                        size="small"
                        color="#1E74FD"
                        shape="round"
                        @click="handleReceive(item, 1)"
                        >接收任务
                      </nut-button>
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <view class="loading-status">
              <view
                class=""
                v-if="loading"
              >
                加载中...
              </view>
              <text v-if="noMoreData">没有更多数据了</text>
            </view>
          </scroll-view>
        </nut-tab-pane>
      </nut-tabs>
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, toRefs } from "vue";
import { navigateTo, useDidShow } from "@tarojs/taro";
import { getRecipientTaskList, getTaskReceiveEdit } from "@/api/index";
import Taro from "@tarojs/taro";
import { getDicts } from "@/utils/utils";
import { IMyTask } from "./type";

const tabs = ref([
  { id: 0, title: "全部", content: "内容1" },
  { id: 1, title: "待处理", content: "内容2" },
  { id: 2, title: "进行中", content: "内容3" },
  { id: 3, title: "已完成", content: "内容3" },
  { id: 4, title: "逾期", content: "内容3" },
]);
const userId = ref(Taro.getStorageSync("user").userId);
const priorityLevelList = ref([
  {
    value: "1",
    text: "S级",
    color: "#FF0000",
    checked: true,
  },
  {
    value: "2",
    text: "A级",
    color: "#FF7300",
    checked: false,
  },
  {
    value: "3",
    text: "B级",
    color: "#FF9100",
    checked: false,
  },
]);
const officeStatusList = ref([]); // 办理状态
const scrollViewHeight = ref("100vh"); // 滚动区域高度
const activeTab = ref(0);
const noMoreData = ref(false); // 是否没有更多数据
const myTaskRecipientList = ref([]);
const loading = ref(false); // 加载状态
const initData: IMyTask = {
  pageNum: 1,
  pageSize: 10,
};
const data = reactive<PageData<IMyTask>>({
  state: { ...initData },
});
const { state } = toRefs(data);
const isMyParticipateTask = ref(false); // 是否是我参与的任务

// Tabs 切换时同步 Swiper
// const handleTabChange = index => {
//   activeTab.value = index;
// };
onMounted(async () => {
  officeStatusList.value = await getDicts("office_status");
  setScrollViewHeight();
  initLoad();
  handleGetTaskRecipientList();
});
useDidShow(() => {
  initLoad();
  handleGetTaskRecipientList();
  // handleGetTaskCreatorsTaskList();
});
const tabClick = (res: { paneKey: number }) => {
  activeTab.value = res.paneKey;
  handleGetTaskRecipientList();
};
const tabChange = (res: { paneKey: number }) => {
  activeTab.value = res.paneKey;
  handleGetTaskRecipientList();
};
// 接收/完成任务
const handleReceive = (item: { taskId: string; taskStatus: number }, status: number) => {
  let params = {
    taskId: item.taskId,
    taskStatus: status,
    userId: userId.value,
  };
  getTaskReceiveEdit(params).then(res => {
    Taro.showToast({
      title: "操作成功",
      icon: "success",
      duration: 2000,
    });
    handleGetTaskRecipientList();
  });
};
//
// const handleSwiperChange = e => {
//   activeTab.value = e.detail.current;
// };
const handleTaskDeails = () => {
  console.log("查看详情");
  navigateTo({
    url: "/packageB/pages/taskManagement/taskDetails/index",
  });
};
// 编辑
const handleEditTask = (item: { taskId: string }) => {
  console.log("编辑");
  navigateTo({
    url: "/packageB/pages/addTask/index?type=edit" + "&taskId=" + item.taskId,
  });
};
// 获取任务我的任务列表
const handleGetTaskRecipientList = () => {
  // if (loading.value || noMoreData.value) return;
  myTaskRecipientList.value = [];
  let taskStatus = activeTab.value - 1;
  taskStatus = taskStatus == -1 ? "" : taskStatus;
  let params = {
    ...state.value,
    userId: userId.value,
    taskStatus: taskStatus,
  };
  getRecipientTaskList(params).then(res => {
    // 如果是第一页，直接替换数据
    if (state.value.pageNum === 1) {
      myTaskRecipientList.value = res.rows;
    } else {
      // 追加数据
      myTaskRecipientList.value = [...myTaskRecipientList.value, ...res.rows];
    }
    // 判断是否还有更多数据
    if (res.rows.length < state.value.pageSize) {
      noMoreData.value = true;
    } else {
      state.value.pageNum++;
    }
    myTaskRecipientList.value.map(item => {
      item.isMyParticipateTask = false;
      item.stausClass = "";
      switch (
        item.taskStatus // 任务状态
      ) {
        case 0:
          item.stausClass = "active1"; // 待处理
          break;
        case 1:
          item.stausClass = "active2"; // 进行中
          break;
        case 2:
          item.stausClass = "active3"; // 已完成
          break;
        case 3:
          item.stausClass = "active4"; // 逾期
          break;
        default:
          break;
      }
      item.isMyParticipateTask = //本人是否是协作人或执行人   个人才能完成任务，公开任务只有执行人才能完成
        item.executorNameList.every((item1, index) => item1.userId == userId.value) ||
        item.collaboratorsNameList.every((item1, index) => item1.userId == userId.value);
      item.isExecutorNameTask = //本人是否是执行人
        item.executorNameList.every((item1, index) => item1.userId == userId.value) ||
        item.collaboratorsNameList.every((item1, index) => item1.userId == userId.value);
    });
  });
};
// 初始化加载
const initLoad = () => {
  state.value.pageNum = 1;
  noMoreData.value = false;
  myTaskRecipientList.value = [];
  handleGetTaskRecipientList();
};
// 设置滚动区域高度
const setScrollViewHeight = () => {
  Taro.getSystemInfo().then(res => {
    // 根据实际情况调整，比如减去导航栏高度等
    scrollViewHeight.value = `${res.windowHeight}px`;
  });
};

// 下拉刷新
const onPullDownRefresh = () => {
  initLoad();
  Taro.stopPullDownRefresh();
};
const loadMore = () => {
  if (!noMoreData.value) {
    handleGetTaskRecipientList();
  }
};
</script>

<style lang="less">
@import "./index.less";
</style>
